package com.gpay.robert.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Copyright (C), 2020-2020
 * FileName: DingdingController
 * Author:   luiz
 * Date:     2020/9/15 15:54
 * Description: 钉钉报警
 */
@RestController
@RequestMapping("/app")
public class RobertController {
    private static final Logger logger= LoggerFactory.getLogger(RobertController.class);

    @Autowired
    private RestTemplate restTemplate;
    @Value("${app.robert.url:https://qyapi.weixin.qq.com/cgi-bin/webhook/send}")
    private  String robertUrl;
    @Value("${app.robert.token}")
    private  String robertToken;
    private static final int limitNum=20;
    //机器人列表
    private static final Map<String,RobertStatic> robertMap=new HashMap<String,RobertStatic>();
    //消息队列
    private ArrayBlockingQueue<String> msgQue=new ArrayBlockingQueue<String>(10240);

    @PostConstruct
    public void initRobertData(){
        //初始化机器人列表
        String[] robertArray=robertToken.split(",");
        for(int i=0;i<= robertArray.length-1;i++){
            RobertStatic robertStatic=new RobertStatic();
            Date nowDate=new Date();
            long startTime=nowDate.getTime();
            robertStatic.setStartTime(startTime);
            robertStatic.setLimitNum(limitNum);
            robertStatic.setRoberToken(robertArray[i]);
            robertStatic.setRoberUrl(robertUrl+"?key="+robertArray[i]);
            robertMap.put(robertStatic.getRoberToken(),robertStatic);
        }
        //消费者线程开启
        new Thread(new MsgConsumer()).start();
    }


    /*
     预警信息发送
     */
    @RequestMapping("/msgAlert")
    public void msgProduce(HttpServletRequest request){
        String reqContent= null;
        try {
            reqContent = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
       logger.info("接受内容：{}",reqContent);
        JSONObject reqJson=JSONObject.parseObject(reqContent);
        JSONArray alertArray=reqJson.getJSONArray("alerts");
        for(int i=0;i<=alertArray.size()-1;i++){
            JSONObject alertJson=(JSONObject) alertArray.get(i);
            String status=alertJson.getString("status");
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("msgtype","markdown");
            JSONObject contentJson=new JSONObject();
            StringBuffer stb=new StringBuffer();
            if("firing".equals(status)){
                //红色
                stb.append("# <font color=\"warning\">Prometheus告警</font>\n");
            }else {
                //绿色
                stb.append("# <font color=\"info\">Prometheus恢复</font>\n");
            }
            if(alertJson.getJSONObject("labels").containsKey("alertname")){
                stb.append("**AlertName**:").append("\n").append(alertJson.getJSONObject("labels").get("alertname")).append("\n");
            }else{
                stb.append("**AlertName**:").append("\n").append("none").append("\n");
            }
            if(alertJson.getJSONObject("labels").containsKey("instance")){
                stb.append("**Instance**:").append("\n").append(alertJson.getJSONObject("labels").get("instance")).append("\n");
            }else {
                stb.append("**Instance**:").append("\n").append("none").append("\n");
            }
            stb.append("**Status**:").append("\n").append(status).append("\n");
            stb.append("**StartsAt**:").append("\n").append(alertJson.get("startsAt")).append("\n");
            stb.append("**EndsAt**:").append("\n").append(alertJson.get("endsAt")).append("\n");
            stb.append("**Message**:").append("\n").append(alertJson.getJSONObject("annotations").get("message")).append("\n");
            contentJson.put("content",stb.toString());
            jsonObject.put("markdown",contentJson);
            //消息存放队列
            this.putQueMsg(jsonObject.toJSONString());
        }
    }
    private String takeQueMsg() {
        try {
            return msgQue.take();
        } catch (InterruptedException e) {
            logger.error("队列出消息发生异常：{}",e);
        }
        return null;
    }

    private void putQueMsg(String sendJson) {
        try {
            msgQue.put(sendJson);
        } catch (InterruptedException e) {
            logger.error("队列存放消息发生异常：{}",e);
        }
    }

    /**
     * 消费者消费消息
     */
    private class MsgConsumer implements Runnable{
        @Override
        public void run() {
            while(1==1){
                String sendJson= takeQueMsg();
                logger.info("消费者开始消费:{}",sendJson);
                if(ObjectUtils.isEmpty(sendJson))continue;
                RobertStatic robertStatic=findAvailableUrl(robertMap);
                if(ObjectUtils.isEmpty(robertStatic))continue;
                //发送前更新发送信息
                updateRobertMap(robertStatic);
                boolean sendFlag=sendDingDingMsg(robertStatic.getRoberUrl(),sendJson);
                if(!sendFlag){
                    putQueMsg(sendJson);
                }
                try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    logger.error("线程休眠发生中断异常:{}",e);
                }
            }

        }
        /**
         * 修改机器人发送信息
         * @param robertStatic
         */
        private void updateRobertMap(RobertStatic robertStatic) {
            Date nowTime=new Date();
            if(robertStatic.getEndTime()<nowTime.getTime()){
                //开始时间、发送次数初始化
                robertStatic.setStartTime(nowTime.getTime());
                robertStatic.setSendNum(0);
            }
            robertStatic.setSendNum(robertStatic.getSendNum()+1);//发送次数
            robertMap.put(robertStatic.getRoberToken(),robertStatic);
        }

        private RobertStatic findAvailableUrl(Map<String, RobertStatic> robertMap) {
            Date nowTime=new Date();
            for(String robertKey:robertMap.keySet()){
                RobertStatic robertStatic=robertMap.get(robertKey);
                logger.info("机器人token:{}发送次数:{},统计值:{}",robertKey,robertStatic.getSendNum(),robertStatic);
                if(robertStatic.getEndTime()<nowTime.getTime()){
                    return robertStatic;
                }
                if(robertStatic.getEndTime()>nowTime.getTime()&&robertStatic.getSendNum()<robertStatic.getLimitNum()){
                    return robertStatic;
                }
            }
            return null;
        }

        private boolean sendDingDingMsg(String robertUrl,String sendMsg){
            try{
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<String> request = new HttpEntity<>(sendMsg, headers);
                logger.info("【机器人】请求地址:{}请求内容:{}",robertUrl,sendMsg);
                ResponseEntity<String> postForEntity = restTemplate.postForEntity(robertUrl, request, String.class);
                String body = postForEntity.getBody();
                logger.info("【机器人】返回内容:{}",body);
                JSONObject respJson=JSON.parseObject(body);
                if(respJson.getIntValue("errcode")==0){
                    return true;
                }
            }catch (Exception e){
                logger.error("【机器人】发送异常:{}",e);
            }
            return false;
        }
    }

}
